package com.maikang.exammall.api;

import com.maikang.exammall.entity.dto.ResponseDTO;
import com.maikang.exammall.entity.dto.WxEnterDTO;
import com.maikang.exammall.service.WxEnterService;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.maikang.exammall.entity.constant.WxConstant.urlPrefix;

@Log4j2
@RestController
@RequestMapping("/wx/redirect")
public class WxRedirectController {
    private final WxMpService wxMpService;
    private final WxEnterService wxEnterService;
    private final String appid;

    @Autowired
    public WxRedirectController(WxMpService wxMpService, WxEnterService wxEnterService) {
        this.wxMpService = wxMpService;
        this.wxEnterService = wxEnterService;
        this.appid = wxMpService.getWxMpConfigStorage().getAppId();
    }

    @GetMapping("/greet")
    public String greetUser(@RequestParam String code, ModelMap map) {
        /**
         * unknown function
         */
        if (!this.wxMpService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            map.put("user", user);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return "greet_user";
    }

    /**
     * @param uri 需要设置的button入口， eg: '/index.html'
     * @return
     */
    @GetMapping("/enter-url")
    public String enterUrl(@RequestParam("uri") String uri) {
        return wxMpService.getOAuth2Service().buildAuthorizationUrl(urlPrefix + uri, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }

    @GetMapping("/enter")
    public ResponseDTO<WxEnterDTO> enter(@RequestParam("code") String code, @RequestParam(required = false, value = "lang") String lang, @RequestParam(defaultValue = "0", required = false, value = "refererId") long refererId) {
        WxOAuth2AccessToken accessToken;
        WxMpUser wxMpUser;
        try {
            accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            wxMpUser = wxMpService.getUserService().userInfo(accessToken.getOpenId(), lang);
            return ResponseDTO.ok(wxEnterService.enter(wxMpUser, accessToken, code, refererId));
        } catch (WxErrorException e) {
            log.error("enter failed, ", e);
            return ResponseDTO.failed(e.getMessage());
        }
    }

}
